package org.xhy.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.xhy.security.filter.SmsAuthenticationFilter;
import org.xhy.security.handler.MyAuthenticationFailureHandler;
import org.xhy.security.handler.MyAuthenticationSuccessHandler;
import org.xhy.security.provider.SmsAuthenticationProvider;
import org.xhy.security.service.MyUserDetailService;

//security 的配置
@Configuration
@EnableWebSecurity  //开启Security
public class SmsAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDetailService myUserDetailService ;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    public  void configure(HttpSecurity http) throws Exception {

        //短信验证码登录=========================================================================================start
        //短信认证Filter
        SmsAuthenticationFilter smsAuthFilter = new SmsAuthenticationFilter();

        smsAuthFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        //设置认证管理器
        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));


        //短信认证provider
        SmsAuthenticationProvider smsDaoAuthenticationProvider = new SmsAuthenticationProvider();
        smsDaoAuthenticationProvider.setMyUserDetailService(myUserDetailService);


        //添加短信认证provider
        http.authenticationProvider(smsDaoAuthenticationProvider);

        //添加短信认证filter
        http.addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);

        //短信验证码登录=========================================================================================end
    }
}